<template>
	<view class="container">
		<view class="s_card radius">
			<view class="countdownBox">
				<!-- <view class="circle">
					<view class="countdownTime" :class="{'wanring': timeS<120}">{{countdownTime}}</view>
					<view style="display: flex;flex-direction: row;align-items: center;"><span style="color:#e4393c;font-size:26px;font-weight:600">{{advanceAmount.toFixed(2)}}
						</span> 元</view>
				</view> -->
				<countdown :fillTime="fillTime" :time="time" :payDate="payDate" :stop="stop" @stoped="onstop"></countdown>
			</view>
			<view class="submit">
				<view class="submitBtn" @click="stopConsume">{{stopBtn}}</view>
			</view>
			<view class="tip">
				<uni-icons type="info" color="#007AFF"></uni-icons>
				为避免长时间占用水控机，预付1元最多用水20分钟，预付2元最多用水40分钟，以此类推。<text class="tip_time">实际扣费以流量（用水量）为准，</text>超时将自动停水结算，您也可以手动点击【结束】按钮提前完成此次消费
			</view>
		</view>
	</view>
</template>

<script>
	import countdown from '@/components/countdown/countdown.vue'
	import {
		getOpenid,
		queryOrderList,
		stopDevice,
		queryConsumeStatus,
		ICPayEnd,
	} from '../../common/api/hot_water.js'
	import {
		isNull,
		strToDate
	} from '../../common/js/utils.js'
	let _this
	export default {
		components: {
			countdown
		},
		data() {
			return {
				fillTime: 0,
				time: 0, // 预付时间 秒钟
				timeS: 0,
				payDate: '',
				// countdownTime: '00:00:00',
				timer: null,
				statusTimer: null,
				machNo: 0, // 机号
				cardNo: 0, // 卡号,
				orgId: "", //结构id
				advanceAmount: 1,
				consumptionId: uni.getStorageSync('consumptionId'), // 热水卡消费记录序列号
				payType: uni.getStorageSync('payType'), // 热水卡消费支付方式
				user: uni.getStorageSync('userInfo'), // 用户信息
				balance: 0,
				stopBtn: '结束',
				stop: false,
				guid: uni.getStorageSync('guid')
				// machineMsg: {}
			}
		},
		onBackPress() {},
		onLoad(option) {
			_this = this
			// _this.machineMsg = JSON.parse(option.machineMsg)
			setTimeout(() => {
				if (!isNull(uni.getStorageSync('consumptionId'))) {
					uni.showLoading({
						title: '数据加载中...'
					});
					if (this.payType == 3) {
						this.getConsumeStatusForCard()
					} else {
						this.getConsumeStatusForWP()
					}
				} else {
					uni.reLaunch({
						url: '../../hotWater/index/index'
					})
				}
			}, 0)
		},
		methods: {
			// 返回消费首页
			countdownBack(time = 4) {
				clearTimeout(this.timer)
				this.stopBtn = time + '秒后返回消费首页'
				if (time < 0) {
					uni.switchTab({
						url: '../../hotWater/index/index'
					})
				} else {
					this.timer = setTimeout(() => {
						this.countdownBack(time - 1)
					}, 1000)
				}
			},
			// 结束消费请求
			stopConsume() {
				uni.showModal({
					title: '消费提示',
					content: '停止消费后将不再供水，如要继续使用，请至首页点击扫码或输入编号再次开闸用水，是否确定停止消费？',
					confirmColor: "#007AFF",
					success: function(res) {
						if (res.confirm) {
							if (_this.payType == 3) {
								uni.showLoading({
									mask: true,
									title: '消费结算中...'
								})
								ICPayEnd({
									cardNo: _this.cardNo,
									expand: 0,
									machNo: _this.machNo,
									orgId: _this.user.orgId,
									guid: _this.guid
								}).then(res => {
									uni.hideLoading()
									if (res.code === 0 && res.data.resultCode === 0) {
										_this.stop = true
										clearTimeout(_this.statusTimer)
										uni.removeStorageSync('consumptionId')
										uni.removeStorageSync('guid')
									} else {
										uni.showToast({
											title: res.data.resultMsg,
											icon: 'none',
											duration: 2500
										})
									}

								})
							} else {
								stopDevice({
									machNo: _this.machNo,
									orgId: _this.orgId,
									flag: _this.payType,
									guid: _this.guid
								}).then(res => {
									if (res.resultCode == 0) {
										_this.stop = true
										clearTimeout(_this.statusTimer)
										uni.removeStorageSync('consumptionId')
										uni.removeStorageSync('guid')
									} else {
										uni.showToast({
											title: res.resultMsg,
											icon: 'none',
											duration: 2500
										})
									}
								}).catch(err => {
									console.log(err)
								})
							}
						}
					}
				})
			},
			// 监听当前消费状态 --- 微信&支付宝
			addStatusListenerWP() {
				clearTimeout(this.statusTimer)
				this.statusTimer = setTimeout(() => {
					if (uni.getStorageSync('consumptionId') == '') {
						clearTimeout(this.statusTimer)
						return
					}
					queryOrderList({
						'consumptionId': uni.getStorageSync('consumptionId')
					}).then(res => {
						if (res.code == 0) {
							let timeS = parseInt(res.data.list[0].advanceTime - ((new Date()).getTime() - (strToDate(res.data.list[0].payTime))
								.getTime()) / 1000)
							if (res.data.list[0].payStatus == 2 && res.data.list[0].refundStatus == 1 && timeS > 0 && !this.stop) {
								_this.addStatusListenerWP()
							} else if (res.data.list[0].payStatus == 2 && res.data.list[0].refundStatus == 2) {
								clearTimeout(_this.statusTimer)
								// _this.countdownTime = '消费结束'
								_this.stopBtn = '3秒后返回消费首页'
								this.stop = true
								// uni.showModal({
								// 	title: '消费提示',
								// 	content: `消费结束！本次消费金额：${res.data.list[0].consumeAmount == null ? 0 : res.data.list[0].consumeAmount}元，返还预付金额${res.data.list[0].refundAmount}`,/* ，返还预付金额${res.refundAmount} */
								// 	showCancel: false,
								// 	confirmColor: "#007AFF",
								// 	success(res) {
								// 		if (res.confirm) {
								// 			uni.removeStorageSync('consumptionId')
								// 			uni.removeStorageSync('guid')
								// 			uni.switchTab({
								// 				url: '../../hotWater/index/index'
								// 			})
								// 		}
								// 	}
								// })
							}
						} else {
							uni.showToast({
								title: '提示',
								content: res.resultMsg,
								icon: "none"
							})
						}
					}).catch(err => {
						console.log(err)
					})
				}, 5000)
			},
			// 监听当前消费状态 --- IC卡消费
			addStatusListenerCard() {
				clearTimeout(this.statusTimer)
				this.statusTimer = setTimeout(() => {
					if (uni.getStorageSync('consumptionId') == '') {
						clearTimeout(this.statusTimer)
						return
					}
					queryConsumeStatus({
						'consumptionId': uni.getStorageSync('consumptionId')
					}).then(res => {
						if (res.resultCode == 0) {
							let timeS = parseInt(res.advanceTime * 60 - ((new Date()).getTime() - (strToDate(res.payTime)).getTime()) /
								1000)
							if (res.payStatus == 1 && timeS > 0) {
								_this.addStatusListenerCard()
							} else if (res.payStatus == 2) {
								clearTimeout(_this.statusTimer)
								this.stop = true
								// uni.showModal({
								// 	title: '消费提示',
								// 	content: `消费结束！本次消费${res.consumeAmount == null ? 0 : res.consumeAmount}元，返还预付金额${res.refundAmount}`,
								// 	showCancel: false,
								// 	confirmColor: "#007AFF",
								// 	success(res) {
								// 		if (res.confirm) {
								// 			uni.removeStorageSync('consumptionId')
								// 			uni.removeStorageSync('guid')
								// 			uni.reLaunch({
								// 				url: '../../hotWater/index/index'
								// 			})
								// 		}
								// 	}
								// })
							}
						} else {
							uni.showToast({
								title: '提示',
								content: res.resultMsg,
								icon: "none"
							})
						}
					}).catch(err => {
						console.log(err)
					})
				}, 5000)
			},
			// 首次加载当前消费状态 --- 微信&支付宝
			getConsumeStatusForWP() {
				clearTimeout(this.statusTimer)
				queryOrderList({
					'consumptionId': uni.getStorageSync('consumptionId')
				}).then(res => {
					if (res.code === 0) {
						let timeS = parseInt(res.data.list[0].advanceTime - ((new Date()).getTime() - (strToDate(res.data.list[0].payTime))
								.getTime()) /
							1000)
						if (res.data.list[0].payStatus == 1) {
							this.statusTimer = setTimeout(() => {
								this.getConsumeStatusForWP()
							}, 2000)
						} else if (res.data.list[0].payStatus == 2 && res.data.list[0].refundStatus == 1 && timeS > 0) {
							uni.hideLoading();
							this.stop = false
							this.advanceAmount = res.data.list[0].advanceAmount
							this.fillTime = res.data.list[0].advanceTime
							this.orgId = res.data.list[0].orgId
							this.machNo = res.data.list[0].deviceNo
							this.timeS = timeS
							this.time = timeS
							this.payDate = res.data.list[0].payTime
							this.addStatusListenerWP()
						} else {
							uni.removeStorageSync('consumptionId')
							uni.removeStorageSync('guid')
							uni.reLaunch({
								url: '../../hotWater/index/index'
							})
						}
					} else {
						AlertModule.show({
							title: '提示',
							content: res.resultMsg
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},
			// 首次加载当前消费状态 --- IC卡
			getConsumeStatusForCard() {
				clearTimeout(this.statusTimer)
				queryConsumeStatus({
					'consumptionId': uni.getStorageSync('consumptionId')
				}).then(res => {
					uni.hideLoading();
					if (res.resultCode == 0) {
						let timeS = parseInt(res.advanceTime * 60 - ((new Date()).getTime() - (strToDate(res.payTime)).getTime()) /
							1000)
						if (res.payStatus == 1 && timeS > 0) {
							uni.hideLoading();
							this.stop = false
							this.advanceAmount = res.advanceAmount
							this.fillTime = res.advanceTime * 60
							this.orgId = res.orgId
							this.machNo = res.deviceNo
							this.timeS = timeS
							this.time = timeS
							this.cardNo = res.cardNo
							this.payDate = res.payTime
							this.addStatusListenerCard()
						} else {
							uni.removeStorageSync('consumptionId')
							uni.reLaunch({
								url: '../../hotWater/index/index'
							})
						}
					}
				}).catch(err => {
					uni.hideLoading();
					console.log(err)
				})
			},
			onstop(newVal) {
				uni.removeStorageSync('consumptionId')
				uni.removeStorageSync('guid')
				uni.reLaunch({
					url: '../../hotWater/index/index'
				})
				// uni.showModal({
				// 	title: '提示',
				// 	content: '消费结束！将在一分钟内进行结算，如有退款，将原路退回支付账户，感谢您的使用！',
				// 	showCancel: false,
				// 	confirmColor: "#007AFF",
				// 	success(res) {
				// 		if (res.confirm) {
				// 			uni.removeStorageSync('consumptionId')
				// 			uni.removeStorageSync('guid')
				// 			uni.reLaunch({
				// 				url: '../../hotWater/index/index'
				// 			})
				// 		}
				// 	}
				// })
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding-top: 24rpx;
		.countdownBox {
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			// padding: 50px 0;

			// .circle {
			// 	height: 200px;
			// 	width: 200px;
			// 	display: flex;
			// 	flex-direction: column;
			// 	justify-content: center;
			// 	align-items: center;
			// 	border: 2px solid #3671b8;
			// 	border-radius: 50%;

			// 	.countdownTime {
			// 		font-size: 34px;
			// 		font-weight: 600;
			// 		color: #007AFF;
			// 		margin: 26px 0;

			// 		&.wanring {
			// 			color: #e4393c;
			// 		}
			// 	}
			// }
		}

		.tip {
			// display: flex;
			// flex-direction: row;
			padding: 12upx;
			font-size: 28upx;
			color: #999;
			margin-top: 30px;
			line-height: 28px;
		}
		
		.tip_time {
			font-size: 44upx;
			line-height: 50upx;
			font-weight: bolder;
			text-align: center;
			// padding: 20px;
			color: #007AFF;
		}
	}
</style>
